package com.ymatou.iapi.trading.sellerquery2.parameter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ymatou.query.seller.trading.api.parameter.SellerExportOrderQueryModel;
import com.ymatou.query.seller.trading.api.parameter.Sp_GetExportOrderInfoByOrderIds_v1;
import com.ymatou.query.seller.trading.api.parameter.Sp_GetExportProductInfoByOrderIds_v1;
import com.ymttest.common.enums.LogisticsTypeEnum;
import com.ymttest.common.enums.OrderStatusEnum;
import com.ymttest.database.sqlwapper.YmtOrdersWapper;
import com.ymttest.utils.DataUtil;

public class ExportOrderInfo {
	public final static Integer MAX_PER_QUERY_COUNT = 1000;

	static int sellerId;
	static List<Integer> orderStatusXml;
	static List<Integer> catalogStatusXml;
	static String BuyerNickName;
	static String ProductName;
	static Boolean paidInFull;
	static Integer OrderId;
	static String AddBeginTime;
	static String AddEndTime;
	static String PaidBeginTime;
	static String PaidEndTime;
	static String DispathBeginTime;
	static String DispathEndTime;
	static String ApplyPostPayBeginTime;
	static String ApplyPostPayEndTime;

	public static void ConstructOrderStatusProperty(
			SellerExportOrderQueryModel model, List<Integer> orderStatusEnum,
			List<Integer> logisticsTypes) {
		if (logisticsTypes != null && logisticsTypes.size() > 0) {
			model.setLogisticsTypeList(logisticsTypes);
		}

		if (orderStatusEnum == null || orderStatusEnum.size() == 0) {
			return;
		}

		List<Integer> orderStatus = new ArrayList<Integer>();
		Boolean bPaidInFull = null;
		boolean orderPostPayFlag = false;
		boolean sellerAcceptFlag = false;

		for (int status : orderStatusEnum) {
			if (status == OrderStatusEnum.OrderEstablish.getValue()) {
				orderStatus.add(1);
			} else if (status == OrderStatusEnum.OrderPostPay.getValue()) {
				orderPostPayFlag = true;
			} else if (status == OrderStatusEnum.SellerAccept.getValue()) {
				sellerAcceptFlag = true;
			} else {
				orderStatus.add(status);
			}
		}

		if (orderPostPayFlag || sellerAcceptFlag) {
			orderStatus.add(17);

			if (orderPostPayFlag && !sellerAcceptFlag)
				bPaidInFull = false;
			if (!orderPostPayFlag && sellerAcceptFlag)
				bPaidInFull = true;
		}

		model.setOrderStatus(orderStatus);
		model.setPaidInFull(bPaidInFull);
	}

	public static void getSqlVarsFromModel(SellerExportOrderQueryModel model) {
		sellerId = model.getSellerId();
		orderStatusXml = model.getOrderStatus();
		catalogStatusXml = model.getLogisticsTypeList();
		BuyerNickName = model.getBuyerNickName();
		ProductName = model.getProductName();
		paidInFull = model.getPaidInFull();
		OrderId = model.getOrderId();
		if (model.getCreatedTime() == null) {
			AddBeginTime = null;
			AddEndTime = null;
		} else {
			AddBeginTime = model.getCreatedTime().getBegin();
			AddEndTime = model.getCreatedTime().getEnd();
		}
		if (model.getPaidTime() == null) {
			PaidBeginTime = null;
			PaidEndTime = null;
		} else {
			PaidBeginTime = model.getPaidTime().getBegin();
			PaidEndTime = model.getPaidTime().getEnd();
		}
		if (model.getDeliveredTime() == null) {
			DispathBeginTime = null;
			DispathEndTime = null;
		} else {
			DispathBeginTime = model.getDeliveredTime().getBegin();
			DispathEndTime = model.getDeliveredTime().getEnd();
		}
		if (model.getPostpayAppliedTime() == null) {
			ApplyPostPayBeginTime = null;
			ApplyPostPayEndTime = null;
		} else {
			ApplyPostPayBeginTime = model.getPostpayAppliedTime().getBegin();
			ApplyPostPayEndTime = model.getPostpayAppliedTime().getEnd();
		}
	}

	public static boolean GetExportSellerOrderInfoExistsSqlCommand(
			SellerExportOrderQueryModel model) {
		getSqlVarsFromModel(model);
		return GetExportSellerJudgementExistsSqlCommand(model);
	}
	
	public static boolean GetExportSellerProductInfoExistsSqlCommand(SellerExportOrderQueryModel model) {
		getSqlVarsFromModel(model);
		return GetExportSellerJudgementExistsSqlCommand(model);
	}

	@SuppressWarnings("rawtypes")
	public static Sp_GetExportProductInfoByOrderIds_v1 GetExportSellerProductInfoListSqlCommand(
			SellerExportOrderQueryModel model) {
		getSqlVarsFromModel(model);
		EnumListValueStatusValidation(model);
		StringBuffer queryField = new StringBuffer();
		String s = "";
		if (hasProductNameValue || hasLogisticsTypeValue) {
			s = "distinct";
		}
		queryField.append(s + " top " + MAX_PER_QUERY_COUNT + " o.iOrderId");
		StringBuffer joinCondition = new StringBuffer();
		StringBuffer queryCondition = new StringBuffer();
		ConstructQueryCondition(model, joinCondition, queryCondition);
		if (false == DataUtil.Stringg.isNullOrEmpty(model.getPartitionKey())) {
			queryCondition.append(" and o.iOrderId < "
					+ model.getPartitionKey());
		}
		queryCondition.append(" order by o.iOrderId desc");
		List<Map> iOrderIds = new YmtOrdersWapper().selectOrders2(
				queryField.toString(), joinCondition.toString(),
				queryCondition.toString());
		List<Integer> orderIds = new ArrayList<Integer>();
		for (Map m : iOrderIds) {
			orderIds.add((Integer) m.get("iOrderId"));
		}
		Sp_GetExportProductInfoByOrderIds_v1 sp = new Sp_GetExportProductInfoByOrderIds_v1(
				orderIds, sellerId);
		return sp;
	}
	
	@SuppressWarnings("rawtypes")
	public static Sp_GetExportOrderInfoByOrderIds_v1 GetExportSellerOrderInfoListSqlCommand(SellerExportOrderQueryModel model){
		getSqlVarsFromModel(model);
		EnumListValueStatusValidation(model);
		StringBuffer queryField = new StringBuffer();
		String s = "";
		if (hasProductNameValue || hasLogisticsTypeValue) {
			s = "distinct";
		}
		queryField.append(s + " top " + MAX_PER_QUERY_COUNT + " o.iOrderId");
		StringBuffer joinCondition = new StringBuffer();
		StringBuffer queryCondition = new StringBuffer();
		ConstructQueryCondition(model, joinCondition, queryCondition);
		if (false == DataUtil.Stringg.isNullOrEmpty(model.getPartitionKey())) {
			queryCondition.append(" and o.iOrderId < "
					+ model.getPartitionKey());
		}
		queryCondition.append(" order by o.iOrderId desc");
		List<Map> iOrderIds = new YmtOrdersWapper().selectOrders2(
				queryField.toString(), joinCondition.toString(),
				queryCondition.toString());
		List<Integer> orderIds = new ArrayList<Integer>();
		for(Map iOrderId:iOrderIds){
			orderIds.add((Integer) iOrderId.get("iOrderId"));
		}
		Sp_GetExportOrderInfoByOrderIds_v1 sp = new Sp_GetExportOrderInfoByOrderIds_v1(orderIds, sellerId);
		return sp;
	}

	public static boolean GetExportSellerJudgementExistsSqlCommand(
			SellerExportOrderQueryModel model) {
		YmtOrdersWapper orderWapper = new YmtOrdersWapper();
		String queryField = " top 1 1";
		StringBuffer queryCondition = new StringBuffer();
		StringBuffer joinCondition = new StringBuffer();
		ConstructQueryCondition(model, joinCondition, queryCondition);
		return orderWapper.selectOrders2(queryField, joinCondition.toString(),
				queryCondition.toString()).size() > 0 ? true : false;
	}

	private static void ConstructQueryCondition(
			SellerExportOrderQueryModel model, StringBuffer joincondition,
			StringBuffer queryCondition) {
		AppendOrderInfoQueryField(model, joincondition);
		AppendBuyerIdQueryField(queryCondition);
		AppendOrderIdQueryField(model, queryCondition);
		AppendAddTimeQueryField(queryCondition);
		AppendPaidTimeQueryField(queryCondition);
		AppendDispathTimeQueryField(queryCondition);
		AppendApplyPostPayTimeQueryField(queryCondition);
		AppendBuyerNickNameQueryField(model, queryCondition);
		AppendOrderStatusQueryField(model, queryCondition);
		AppendPayTypesQueryField(model, queryCondition);
	}

	static boolean hasLogisticsTypeValue;
	static boolean hasProductNameValue;

	private static void EnumListValueStatusValidation(
			SellerExportOrderQueryModel model) {
		hasLogisticsTypeValue = !(DataUtil.isNullOrEmpty(model
				.getLogisticsTypeList()) || (model.getLogisticsTypeList()
				.size() == 1 && model.getLogisticsTypeList().get(0) == LogisticsTypeEnum.Unknown
				.getValue()));
		hasProductNameValue = !DataUtil.Stringg.isNullOrEmpty(model
				.getProductName());
	}

	/**
	 * 商品名称&配送方式
	 * 
	 * @param model
	 * @return
	 */
	private static void AppendOrderInfoQueryField(
			SellerExportOrderQueryModel model, StringBuffer joincondition) {
		EnumListValueStatusValidation(model);
		if (hasProductNameValue == false && hasLogisticsTypeValue == false) {
			return;
		}
		joincondition
				.append(" inner join Ymt_OrderInfo as oi with(nolock) on oi.iOrderId = o.iOrderId");
		if (hasProductNameValue) {
			joincondition.append(" and oi.sTitle like '%" + ProductName + "%'");
		}
		if (hasLogisticsTypeValue) {
			joincondition.append(" and oi.iCatalogStatus in "
					+ DataUtil.toInOfSql(catalogStatusXml));
		}
	}

	/**
	 * 固定买手ID条件
	 * 
	 * @param model
	 * @param sb
	 */
	private static void AppendBuyerIdQueryField(StringBuffer sb) {
		sb.append(" o.iBuyerId = " + sellerId);
	}

	/**
	 * 订单号
	 * 
	 * @param model
	 * @param sb
	 */
	private static void AppendOrderIdQueryField(
			SellerExportOrderQueryModel model, StringBuffer sb) {
		if (model.getOrderId() == null || model.getOrderId() == 0) {
			return;
		}
		sb.append(" and o.iOrderId = " + OrderId);
	}

	/**
	 * 下单时间
	 * 
	 * @param model
	 * @param sb
	 */
	private static void AppendAddTimeQueryField(StringBuffer sb) {
		if (AddBeginTime != null) {
			sb.append(" and o.dAddTime >= '" + AddBeginTime + "'");
		}

		if (AddEndTime != null) {
			sb.append(" and o.dAddTime < '" + AddEndTime + "'");
		}
	}

	/**
	 * 支付时间
	 * 
	 * @param model
	 * @param sb
	 */
	private static void AppendPaidTimeQueryField(StringBuffer sb) {
		if (PaidBeginTime != null) {
			sb.append(" and ( (o.dPostPaidTime is null and o.dPaidTime >= '"
					+ PaidBeginTime + "') or o.dPostPaidTime >= '"
					+ PaidBeginTime + "') ");
		}

		if (PaidEndTime != null) {
			sb.append(" and ( (o.dPostPaidTime is null and o.dPaidTime < '"
					+ PaidEndTime + "') or o.dPostPaidTime < '" + PaidEndTime
					+ "') ");
		}
	}

	/**
	 * 发货时间
	 * 
	 * @param model
	 * @param sb
	 */
	private static void AppendDispathTimeQueryField(StringBuffer sb) {
		if (DispathBeginTime != null) {
			sb.append(" and o.dDispathTime >= '" + DispathBeginTime + "'");
		}

		if (DispathEndTime != null) {
			sb.append(" and o.dDispathTime < '" + DispathEndTime + "'");
		}
	}

	/**
	 * 申请补款时间
	 * 
	 * @param model
	 * @param sb
	 */
	private static void AppendApplyPostPayTimeQueryField(StringBuffer sb) {
		if (ApplyPostPayBeginTime != null) {
			sb.append(" and o.dApplyPostPayTime >= '" + ApplyPostPayBeginTime
					+ "'");
		}

		if (ApplyPostPayEndTime != null) {
			sb.append(" and o.dApplyPostPayTime < '" + ApplyPostPayEndTime
					+ "'");
		}
	}

	/**
	 * 买家昵称
	 * 
	 * @param model
	 * @param sb
	 */
	private static void AppendBuyerNickNameQueryField(
			SellerExportOrderQueryModel model, StringBuffer sb) {
		if (DataUtil.Stringg.isNullOrEmpty(model.getBuyerNickName())) {
			return;
		}

		sb.append(" and o.sBuyerNickName = '" + BuyerNickName + "'");
	}

	/**
	 * 订单状态
	 * 
	 * @param model
	 * @param cmd
	 */
	private static void AppendOrderStatusQueryField(
			SellerExportOrderQueryModel model, StringBuffer cmd) {
		boolean hasOrderStatusValue = !(DataUtil.isNullOrEmpty(model
				.getOrderStatus()) || (model.getOrderStatus().size() == 1 && model
				.getOrderStatus().get(0) == OrderStatusEnum.Unkown.getValue()));

		if (!hasOrderStatusValue) {
			return;
		}
		List<Integer> temp = new ArrayList<Integer>();
		temp.addAll(model.getOrderStatus());

		StringBuilder sb = new StringBuilder();
		if (model.getPaidInFull() != null) {
			sb.append("or (o.iTradingStatus = 17 and o.bPaidInFull = "
					+ DataUtil.bool2Int(paidInFull) + ") ");
			temp.removeIf(x -> x == 17);
		}

		if (temp.size() > 0) {
			sb.append("or o.iTradingStatus in " + DataUtil.toInOfSql(temp));
		}

		// 可能有错
		cmd.append(" and (").append(sb.substring(2).toString()).append(") \n");
	}

	// 定金+尾款 或 全款
	private static void AppendPayTypesQueryField(
			SellerExportOrderQueryModel model, StringBuffer sb) {
		if (DataUtil.isNullOrEmpty(model.getPayTypes())
				|| (model.getPayTypes().contains(0) && model.getPayTypes()
						.contains(1))) {
			return;
		}
		sb.append(" and o.bShangouOrder =  " + model.getPayTypes().get(0));
	}
}
